package com.siecom.client;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.external.changanbank.ConstCA;
import com.external.changanbank.IErrorCallback;
import com.external.changanbank.ISucceedCallback;
import com.external.changanbank.SunyardBankOperation;
import com.external.changanbank.SunyardPeripheral;
import com.external.changanbank.Task;
import com.rey.material.widget.Button;
import com.rey.material.widget.EditText;
import com.rey.material.widget.Spinner;
import com.siecomzg.bean.BankCardInfoBean;
import com.siecomzg.bean.IdentityInfoBean;
import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.tool.ByteTool;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.transport.ConnectStatusCallback;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.SiecomDevice;
import com.siecom.zhq.client.R;

import java.util.Set;


import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Administrator on 2015/12/3.
 * 所有的SDK操作都是以SiecomDevice为入口
 * 使用 SiecomTask.TaskCallback 作为回调的方法都能直接在回调方法内操作界面元素，已经封装了handler在界面执行，除非方法中含有Sync字样，否则均是异步方法，不会堵塞主线程
 * 失败回调固定有错误码和描述，默认内部如IO异常、数组越界等常规错误直接用e.hashcode作为错误码，e.getMessage为信息，其余错误则为本sdk自定义错误。如下
 * int code = bundle.getInt("code");
 * String msg = bundle.getString("message");
 * 成功回调的信息则在bundle内，具体类型和数据请参考本类中的使用
 */
public class ChangAnActivity extends AppCompatActivity {

    public static int packType = 0 ; // 0 原来的  1 zbk  2 siecom liaoning 3 贵州农商 赞同UPD1080

    private SunyardPeripheral peripheral = null;
    private static final String TAG = ChangAnActivity.class.getSimpleName();
    //UI setting
    public TextView deviceName;
    public TextView deviceMac;
    public TextView deviceVersion;
    public ImageView deviceIcon;
    public TextView power;
    private SmoothProgressBar spb = null;
    //TextSpeaker speaker;//语音朗读
    //身份证UI
    private TextView tv_name, tv_sex, tv_nation, tv_birth, tv_address, tv_id,
            tv_police, tv_validate;
    private ImageView ivPhotoes;
    //指纹扫描动画
    private ImageView scan_line;
    private Animation upAnimation;
    private Animation downAnimation;

    private Dialog dialog;
    private BluetoothDevice device;
    private UsbDevice mUsbDevice;
    private String mType = "";
    private LinearLayout mLinearLayout;
    private MaterialDialog pDialog = null;

    public final static int dis_connect = 0;
    public final static int arpc_ret = 1; //接受同步ARPC接口
    public final static int get_log_ret = 2; //接受同步明细接口
    public final static int write_code_name = 3; //接受同步写入编号接口
    public final static int read_code_name = 4; //接受同步读取编号接口
    public final static int read_uniq_name = 5; //接受同步读取唯一号接口
    public final static int test_psam = 6; //接受测试PSAM卡

    public TextView cardInfoText;//银行卡信息
    public TextView codenameStr;//编号的textView
    public TextView uniqstr;//唯一号的textView
    private long now = 0;

    private static final String[] cardTypeStr = {"IC卡", "非接卡", "磁条卡","自动"};

    private static final String[] encryptTypeStr = {"国际", "国密","不加密"};
    // 主密钥
        private static byte[] master_key = ByteTool.hexStr2Bytes("E477E2869494E8196D302C89293193C5");

//    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "siecom" + File.separator ;

    // 工作密钥
//    private static byte[] work_key = {0x12, 0x34, 0x56, 0x78, (byte) 0x90,
//            (byte) 0xab, (byte) 0xcd, (byte) 0xef, 0x01, 0x02, 0x03, 0x04,
//            0x05, 0x06, 0x07, 0x08};
    private static byte[] work_key = ByteTool.hexStr2Bytes("85F754C57D5F47A76CE580B8712D1F24");
//"1234567890abcdef0102030405060708"
    final String bankCardNo = "62145601000000647";// 卡号 62145601000000647
    final String amount = "123456.00";// 金额显示,只做显示用，有些固件版本并无此功能
    private Handler handler = new Handler();

    public int cardType = ConstDefine.IC_CARD;

    public byte encryptType = ConstDefine.KEY_SM;  // 1-3DES   2-SM4   3- 明文

    public boolean isSetEncrypt = false;
    private int mProgress = 0;
    /**
     * 用于加密轨迹数据的密钥
     */
    private static byte[] sm4key = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
            0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_identify);
        LogUtil.e(TAG,"ChangAnActivity onCreate--");
        getSupportActionBar().setTitle("长安银行测试");
        //日志开关
        LogUtil.setLogEnabled(true);
        LogUtil.setLog2File(false);

        deviceName = (TextView) findViewById(R.id.device_name);
        deviceMac = (TextView) findViewById(R.id.device_mac);

        mType = getIntent().getStringExtra("type");
        if(mType.equals("1")){ //蓝牙设备
            device = getIntent().getParcelableExtra("Device");
            deviceName.setText(device.getName());
            deviceMac.setText(device.getAddress());
            //长安银行的接口
            peripheral = new SunyardPeripheral(this);



        }else if (mType.equals("2")){
            mUsbDevice = getIntent().getParcelableExtra("Device");
            deviceName.setText("A108Plus");
//            deviceName.setText(mUsbDevice.getProductName());
            deviceMac.setText("USB连接");
        }
        deviceVersion = (TextView) findViewById(R.id.device_version);



        power = (TextView) findViewById(R.id.power);
        deviceIcon = (ImageView) findViewById(R.id.device_icon);
        spb = (SmoothProgressBar) findViewById(R.id.spb);
        spb.setVisibility(View.INVISIBLE); // wait for runnable
        mLinearLayout = (LinearLayout) findViewById(R.id.info_scroll);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                spb.setVisibility(View.VISIBLE);

                /*
                  首先连接蓝牙
                 */
                if(mType.equals("1")){
                    initLink();
                }else {
                    afterLink();
                }
//                afterLink();
            }
        },200);

    }


    class SpinnerSelectedListener implements Spinner.OnItemSelectedListener {
        @Override
        public void onItemSelected(Spinner parent, View view, int position, long id) {
            if (cardTypeStr[position].equals("IC卡")) {

                cardType = ConstDefine.IC_CARD;
            }

            if (cardTypeStr[position].equals("非接卡")) {
                cardType = ConstDefine.PIC_CARD;

            }
            if (cardTypeStr[position].equals("磁条卡")) {

                cardType = ConstDefine.MSR_CARD;
            }
            if (cardTypeStr[position].equals("自动")) {

                cardType = ConstDefine.AUTO_CARD;
            }

        }
    }


    private void showOtherDialog() {
        final View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.other_layout, null);
        Button writeCodeBtn = (Button) view.findViewById(R.id.write_code_btn);
        Button readCodeBtn = (Button) view.findViewById(R.id.read_code_btn);
        Button readSnBtn = (Button) view.findViewById(R.id.read_sn_btn);
        final EditText codename = (EditText) view.findViewById(R.id.code_name_str);
        codenameStr = (TextView) view.findViewById(R.id.code_text);
        uniqstr = (TextView) view.findViewById(R.id.sn_text);
        final TextView info_text = (TextView) view.findViewById(R.id.info_text);
        Button update_btn = (Button) view.findViewById(R.id.update_btn);
        Button reset_btn = (Button) view.findViewById(R.id.reset_btn);
        Button finger_ver_btn = (Button) view.findViewById(R.id.finger_ver_btn);
        Button testPsam1Btn = (Button) view.findViewById(R.id.testPasm1_btn);
        Button testPsam2Btn = (Button) view.findViewById(R.id.testPasm2_btn);
        Button testLightBtn = (Button) view.findViewById(R.id.test_light_btn);
        Button testSerialBtn = (Button) view.findViewById(R.id.test_serial_btn);
        Button btnApdu = (Button) view.findViewById(R.id.test_apdu_btn);

        android.widget.Button btnReadSocial = (android.widget.Button) view.findViewById(R.id.btn_read_social);
        btnReadSocial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_text.setText("");

            }
        });
        /**
         * 测试apdu
         */
        btnApdu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.e(TAG,"time == " + System.currentTimeMillis());


            }
        });
        /**
         * 测试psam卡
         */
        testPsam1Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.testPsam("1", new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        Toast.makeText(ChangAnActivity.this, "PSAM1 失败!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(ChangAnActivity.this, "PSAM1 OK!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);

            }
        });
        testPsam2Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.testPsam("2", new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        Toast.makeText(ChangAnActivity.this, "PSAM2 失败!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(ChangAnActivity.this, "PSAM2 OK!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);


            }
        });

        testLightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (packType == 0){
                    SiecomDevice.testLight(new DeviceCallback() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onError(Bundle bundle) {

                        }

                        @Override
                        public void onSuccess(Bundle bundle) {

                        }

                        @Override
                        public void onCompleted(Bundle bundle) {

                        }
                    },10*1000,true);
                }



            }
        });
        testSerialBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });


        finger_ver_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.readFingerVersion(new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(ChangAnActivity.this, "version:" + bundle.getString("data"), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 6000, true);


            }
        });
        Button test_btn = (Button) view.findViewById(R.id.test_btn);
        test_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });
        /**
         * 改成升级固件了
         */
        update_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {




            }
        });

        reset_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        writeCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }

        });
        readCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.getCodeName(new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String codeStr = bundle.getString("data");

                        codeStr = codeStr.replace(" ","");
                        codenameStr.setText(codeStr);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);

            }
        });
        readSnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SiecomDevice.getDeviceSN(new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        uniqstr.setText(bundle.getString("data"));
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 6000, true);


            }

        });
        pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                .theme(Theme.LIGHT)
                .title(R.string.other)
                .customView(view, true)
                .positiveText(R.string.no)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {

                        dismissDialog();

                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {


                    }
                })
                .build();
        pDialog.show();

    }

//
    SunyardBankOperation operation = new SunyardBankOperation();

    private void showCardDialog() {
        //默认就是第一个
        dismissDialog();
        final View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.card_dialog_layout, null);
        Button read_card_btn = (Button) view.findViewById(R.id.read_card_btn);
        final Button arpcBtn = (Button) view.findViewById(R.id.arpc_btn);
        final Button getLogBtn = (Button) view.findViewById(R.id.get_log_btn);
        Spinner spinner = (Spinner) view.findViewById(R.id.card_list_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(ChangAnActivity.this, android.R.layout.simple_spinner_item, cardTypeStr);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        cardInfoText = (TextView) view.findViewById(R.id.card_info_text);
        final TextView cardTypeText = (TextView) view.findViewById(R.id.card_type_text);
        final TextView cardNoText = (TextView) view.findViewById(R.id.card_no_text);
        //添加事件Spinner事件监听
        spinner.setOnItemSelectedListener(new SpinnerSelectedListener());

        pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                .theme(Theme.LIGHT)
                .customView(view, true)
                .title(R.string.readCard)
                .positiveText(R.string.no)
                .cancelable(false)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                        dismissDialog();

                        operation.cancerCommd();

                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                        cardType = ConstDefine.IC_CARD;

                    }
                })
                .build();
        pDialog.show();

        read_card_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e("cardType:", cardType + "----");

                String[] wantTags = {"5A", "57", "5F20", "9F62", "9F61", "9F1F", "9F79",
                        "9F77", "5F24", "5F34", "9F26", "9F27", "9F10", "9F37", "9F36",
                        "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33",
                        "9F34"};

                now = System.currentTimeMillis();

                if (cardType == ConstDefine.MSR_CARD){
                    peripheral.addTask(new Task(Task.Operate.READ_MAGNETISM, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            final BankCardInfoBean bean = bundle.getParcelable("data");
                            if (bean.cardType == ConstDefine.MSR_CARD) {
                                cardTypeText.setText(getResources().getString(R.string.MSR));
                                cardNoText.setText(bean.cardNo);
                                cardInfoText.setText("tk1:" + bean.oneMagneticTrack + "\r\n" + "tk2:" + bean.twoMagneticTrack + "\r\n" + "tk3:" + bean.threeMagneticTrack);

                            }
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            int code = bundle.getInt("code");
                            String msg = bundle.getString("message");

                            Snackbar.make(view, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }
                    }));
                }

                if (cardType == ConstDefine.IC_CARD)
                    peripheral.addTask(new Task(Task.Operate.READ_IC_CARD, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            final BankCardInfoBean bean = bundle.getParcelable("data");
                            long finish = System.currentTimeMillis();
                            Snackbar.make(view, getResources().getString(R.string.readComplete) + ":useTime:" + (finish - now) + "ms", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                            if (bean.cardType == ConstDefine.IC_CARD) {
                                cardTypeText.setText(getResources().getString(R.string.ICC));
                                cardNoText.setText(bean.cardNo);
                                cardInfoText.setText(bean.ICChipData);

                            } else if (bean.cardType == ConstDefine.PIC_CARD) {

                                cardTypeText.setText(getResources().getString(R.string.PICC));
                                cardNoText.setText(bean.cardNo);
                                cardInfoText.setText(bean.ICChipData);

                            } else if (bean.cardType == ConstDefine.MSR_CARD) {
                                cardTypeText.setText(getResources().getString(R.string.MSR));
                                cardNoText.setText(bean.cardNo);
                                cardInfoText.setText("tk1:" + bean.oneMagneticTrack + "\r\n" + "tk2:" + bean.twoMagneticTrack + "\r\n" + "tk3:" + bean.threeMagneticTrack);

                            }

                            //如果不是磁卡可以获取交易的明细和做arpc
                            if (bean.cardType != ConstDefine.MSR_CARD) {
                                arpcBtn.setVisibility(View.VISIBLE);
                                getLogBtn.setVisibility(View.VISIBLE);

                            } else {
                                arpcBtn.setVisibility(View.INVISIBLE);
                                getLogBtn.setVisibility(View.INVISIBLE);
                            }
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            int code = bundle.getInt("code");
                            String msg = bundle.getString("message");

                            Snackbar.make(view, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                    }));




            }
        });

    }

    class EncryptSelectedListener implements Spinner.OnItemSelectedListener {
        @Override
        public void onItemSelected(Spinner parent, View view, int position, long id) {

            if (encryptTypeStr[position].equals("国际")) {

                encryptType = ConstDefine.KEY_3DES;
            }
            if (encryptTypeStr[position].equals("国密")) {

                encryptType = ConstDefine.KEY_SM;

            }
            if(encryptTypeStr[position].equals("不加密")){

                encryptType = ConstDefine.KEY_NOENCRYPTION;
            }

            isSetEncrypt = true;
//            setEncrypt();
        }
    }


    /**
     * 密码键盘的界面
     */
    private void showKeyDialog() {

        encryptType = ConstDefine.KEY_3DES; //默认为第一个
        final View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.keypad_dialog, null);
//        Toast.makeText(ChangAnActivity.this, getResources().getString(R.string.need_set_mode), Toast.LENGTH_SHORT).show();

        final TextView main_key = (TextView) view.findViewById(R.id.main_key_text);
        main_key.setText(getResources().getString(R.string.main_key) + ":" + ByteTool.byte2hex(master_key));
        final TextView work_key_text = (TextView) view.findViewById(R.id.work_key_text);
        work_key_text.setText(getResources().getString(R.string.work_key) + ":" + ByteTool.byte2hex(work_key));
        Button input_mkey_btn = (Button) view.findViewById(R.id.input_mkey_btn);
        Button input_wkey_btn = (Button) view.findViewById(R.id.input_wkey_btn);
        Button pubEncMainBtn = (Button) view.findViewById(R.id.btn_test_sm2_encrypt_main);
        final TextView cardNo = (TextView) view.findViewById(R.id.card_no_str);
        TextView amount_text = (TextView) view.findViewById(R.id.amount_str);
        cardNo.setText(getResources().getString(R.string.card_no) + ":" + bankCardNo);
        amount_text.setText(getResources().getString(R.string.amount) + ":" + amount);
        @SuppressLint("WrongViewCast") final AppCompatEditText click_input = (AppCompatEditText) view.findViewById(R.id.click_input);
        click_input.setInputType(InputType.TYPE_NULL);
        click_input.requestFocus();
        Spinner spinner = (Spinner) view.findViewById(R.id.encrypt_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(ChangAnActivity.this, android.R.layout.simple_spinner_item, encryptTypeStr);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new EncryptSelectedListener());
//        pubEncMainBtn.setVisibility(View.INVISIBLE);

        final int mainIndex = 1;
        final int workIndex = 2;

        input_mkey_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (encryptType == ConstDefine.KEY_3DES){
                    Task task = new Task(Task.Operate.MAIN_SECRET_KEY, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString("data"));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            LogUtil.e(TAG,"code = "+ bundle.getInt("code")+ " -- " + bundle.getString("message"));
                        }
                    });
                    String mainKey = "11111111111111112222222222222222";
                    task.setParams(mainKey.getBytes());
                    peripheral.addTask(task);
                }

                if (encryptType == ConstDefine.KEY_SM){
                    Task task = new Task(Task.Operate.WRITE_MAINKEY_SM4, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString("data"));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            LogUtil.e(TAG,"code = "+ bundle.getInt("code")+ " -- " + bundle.getString("message"));
                        }
                    });
                    String mainKey = "11111111111111112222222222222222";
                    task.setPublicKey(mainKey);
                    peripheral.addTask(task);
                }
            }
        });

        input_wkey_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (encryptType == ConstDefine.KEY_3DES){
                    String workKey = "11111111111111112222222222222222";
                    Task task = new Task(Task.Operate.UPDATE_SECRET_KEY, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString("data"));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            click_input.setText("code == "+ bundle.getInt("code") + " --- " + bundle.getString("message"));
                        }
                    });
                    task.setParams(workKey.getBytes());
                    peripheral.addTask(task);
                }
                if (encryptType == ConstDefine.KEY_SM){
                    String workKey = "11111111111111112222222222222222";
                    Task task = new Task(Task.Operate.WRITE_WORKKEY_SM4, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString("data"));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            click_input.setText("code == "+ bundle.getInt("code") + " --- " + bundle.getString("message"));
                        }
                    });
                    task.setPublicKey(workKey);
                    peripheral.addTask(task);
                }

            }
        });

        click_input.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (encryptType == ConstDefine.KEY_3DES){
                    Task task = new Task(Task.Operate.READ_ENCRYPT_3DES_PINBLOCK, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString(ConstCA.password));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            click_input.setText("code == "+ bundle.getInt("code") + " --- " + bundle.getString("message"));
                        }
                    });
                    task.setCardNo("000000000000");
//                    task.setIsVoicePromptReEnterPassword(true);
                    task.setPwdLength(6);
                    peripheral.addTask(task);
                }
                if (encryptType == ConstDefine.KEY_SM){
                    Task task = new Task(Task.Operate.GET_PWD_SM4, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString(ConstCA.password));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            click_input.setText("code == "+ bundle.getInt("code") + " --- " + bundle.getString("message"));
                        }
                    });
                    task.setCardNo("000000000000");
//                    task.setIsVoicePromptReEnterPassword(true);
                    task.setPwdLength(6);
                    peripheral.addTask(task);
                }
                if (encryptType == ConstDefine.KEY_NOENCRYPTION){
                    peripheral.addTask(new Task(Task.Operate.READ_PASSWORD, new ISucceedCallback() {
                        @Override
                        public void onSucceed(Bundle bundle) {
                            click_input.setText(bundle.getString("data"));
                        }
                    }, new IErrorCallback() {
                        @Override
                        public void onError(Bundle bundle) {
                            click_input.setText("code == "+ bundle.getInt("code") + " --- " + bundle.getString("message"));
                        }
                    }));
                }




            }
        });
        String str = getResources().getString(R.string.no);
        pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                .theme(Theme.LIGHT)
                .title(R.string.keyPin)
                .customView(view, true)
                .positiveText(str)
                .cancelable(false)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {

                        dismissDialog();
                    operation.cancerCommd(); // 取消输入密码

                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                    }
                })
                .build();
        pDialog.show();


    }


    /**
     * 读取指纹特征码
     */
    public void readFingerPrint() {
        mFailCount=0;
        mSuccessCount = 0;

        final DeviceCallback deviceCallback = new DeviceCallback() {
            @Override
            public void onStart() {

                View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.layout_finger_scan, null);
                scan_line = (ImageView) view.findViewById(R.id.lockscreen_scan_line);
                upAnimation = AnimationUtils.loadAnimation(ChangAnActivity.this, R.anim.push_up_in);
                upAnimation.setFillAfter(true);
                upAnimation.setAnimationListener(new UpAnimationOnListener());

                downAnimation = AnimationUtils.loadAnimation(ChangAnActivity.this, R.anim.push_up_out);
                downAnimation.setFillAfter(true);
                downAnimation.setAnimationListener(new DownAnimationOnListener());
                scan_line.startAnimation(downAnimation);
                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title(R.string.finger_scan)
                        .positiveText(R.string.no)
                        .cancelable(false)
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                /**
                                 * 取消任务；
                                 */
                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onError(Bundle bundle) {
                                    }

                                    @Override
                                    public void onSuccess(Bundle bundle) {
                                        Toast.makeText(ChangAnActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onCompleted(Bundle bundle) {
                                    }
                                }, 2000, true);


                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                                Snackbar.make(mLinearLayout, "取消指纹后再启动最长可能需要5~7秒", Snackbar.LENGTH_LONG).setAction("Action", null).show();

                            }
                        })
                        .build();
                pDialog.show();
            }

            @Override
            public void onError(Bundle bundle) {
                mFailCount++;

            }

            @Override
            public void onSuccess(Bundle bundle) {
                mSuccessCount ++;
                dismissDialog();
                /**
                 * 获取到指纹特征码，默认使用Base64转一下
                 */



            }

            @Override
            public void onCompleted(Bundle bundle) {
//                pDialog.setTitle("成功"+ mSuccessCount+"次，"+ "失败" + mFailCount + "次");
            }
        };
        peripheral.addTask(new Task(Task.Operate.FINGERPRINT, new ISucceedCallback() {
            @Override
            public void onSucceed(Bundle bundle) {
                String fingerCode = bundle.getString( ConstCA.fingerprintfeature);

                Log.e("fingerPrint:", fingerCode);

                dismissDialog();

                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                        .theme(Theme.DARK)
                        .title(R.string.finger_code)
                        .content(getResources().getString(R.string.your_finger) + ":" + fingerCode)
                        .positiveText(R.string.sure)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                            }
                        })
                        .build();
                pDialog.show();
            }
        }, new IErrorCallback() {
            @Override
            public void onError(Bundle bundle) {
                dismissDialog();
                Snackbar.make(mLinearLayout, bundle.getString("message"), Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }
        }));


    }

    int mSuccessCount = 0,mFailCount = 0;
    /**
     * 读取身份证
     */
    public void readIDcard() {
        Log.e("read", "readIDcard");

        mSuccessCount = 0;
        mFailCount = 0;
        now = System.currentTimeMillis();
        DeviceCallback taskCallback = new DeviceCallback() {
            @Override
            public void onStart() {

                Snackbar.make(mLinearLayout, getResources().getString(R.string.read_id), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                        .title(R.string.read_id)
                        .content(R.string.please_wait)
                        .progress(true, 0)
                        .progressIndeterminateStyle(true)
                        .positiveText(R.string.no)
                        .cancelable(false)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onError(Bundle bundle) {

                                    }

                                    @Override
                                    public void onSuccess(Bundle bundle) {

                                        Toast.makeText(ChangAnActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();

                                    }

                                    @Override
                                    public void onCompleted(Bundle bundle) {

                                    }
                                }, 2000, true);

                            }
                        })
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {

                            }
                        })
                        .build();

                if (!pDialog.isShowing()) {
                    pDialog.show();
                }
            }

            @Override
            public void onSuccess(Bundle bundle) {
                mSuccessCount ++;

            }

            @Override
            public void onCompleted(Bundle bundle) {
                now = System.currentTimeMillis();
                LogUtil.e("身份证------",  "onCompleted!!!!!");

            }

            @Override
            public void onError(Bundle bundle) {
                mFailCount ++;

            }
        };
        peripheral.addTask(new Task(Task.Operate.READ_IDENTITY, new ISucceedCallback() {
            @Override
            public void onSucceed(Bundle bundle) {
                long fin = System.currentTimeMillis();
                Toast.makeText(ChangAnActivity.this, "useTime:" + (fin - now) + "ms", Toast.LENGTH_SHORT).show();
                //获取bean
                IdentityInfoBean bean = bundle.getParcelable("data");

                dismissDialog();

                View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.draw_idcard, null);
                tv_name = (TextView) view.findViewById(R.id.name);
                tv_sex = (TextView) view.findViewById(R.id.sex);
                tv_nation = (TextView) view.findViewById(R.id.nation);
                tv_birth = (TextView) view.findViewById(R.id.birth);
                tv_address = (TextView) view.findViewById(R.id.address);
                tv_id = (TextView) view.findViewById(R.id.id);
                tv_police = (TextView) view.findViewById(R.id.police);
                tv_validate = (TextView) view.findViewById(R.id.validate);
                ivPhotoes = (ImageView) view.findViewById(R.id.touxiang);

                tv_name.setText(bean.fullName);
                tv_sex.setText(bean.sex);
                tv_nation.setText(bean.nation);
                StringBuffer buffer = new StringBuffer();
                buffer.append(bean.birthday.substring(0, 4)).append("        ").append(bean.birthday.substring(4, 6)).append("     ").append(bean.birthday.substring(6, 8));

                tv_birth.setText(buffer.toString());
                tv_address.setText(bean.idAddr);
                tv_id.setText(bean.idNo);
                tv_police.setText(bean.idOrg);
                tv_validate.setText(bean.beginDate + "-" + bean.endDate);

                ivPhotoes.setImageBitmap(bean.icon);
                LogUtil.e(TAG,"照片：" + bean.photodata);
                String str = getResources().getString(R.string.no_finger);
//                str = "成功" + mSuccessCount + "次,失败" + mFailCount + "次" ;
                if (bean.fingerStr != null) {
                    str = getResources().getString(R.string.has_finger);
                    Toast.makeText(ChangAnActivity.this, bean.fingerStr, Toast.LENGTH_SHORT).show();

                }
                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .positiveText(str)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                            }
                        })
                        .build();
                pDialog.show();
            }
        }, new IErrorCallback() {
            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                LogUtil.e("身份证------", msg + "!!!!!");
                Snackbar.make(mLinearLayout, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                dismissDialog();
            }
        }));


    }



    /**
     * 获取指纹图像
     */
    public void getFingerImageViewPrint() {
        mFailCount=0;
        mSuccessCount = 0;
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
            pDialog = null;
        }
        View view = LayoutInflater.from(this).inflate(R.layout.layout_finger_scan, null);
        scan_line = (ImageView) view.findViewById(R.id.lockscreen_scan_line);
        upAnimation = AnimationUtils.loadAnimation(ChangAnActivity.this, R.anim.push_up_in);
        upAnimation.setFillAfter(true);
        upAnimation.setAnimationListener(new UpAnimationOnListener());
        downAnimation = AnimationUtils.loadAnimation(this, R.anim.push_up_out);
        downAnimation.setFillAfter(true);
        downAnimation.setAnimationListener(new DownAnimationOnListener());
        scan_line.startAnimation(downAnimation);

        now = System.currentTimeMillis();

        peripheral.addTask(new Task(Task.Operate.READ_FINGERPRINT_IMAGE, new ISucceedCallback() {
            @Override
            public void onSucceed(Bundle bundle) {
                String fingerCode = bundle.getString( ConstCA.fingerprintfeature);
                Bitmap bitmap = bundle.getParcelable("bitmap");
                LogUtil.e(TAG,"bitmap size == " + bitmap.getByteCount());
//                Log.e("fingerPrint:", fingerCode);

                dismissDialog();
                //                /**
//                 * 获取到指纹特征码，默认使用Base64转一下
//                 */
                dismissDialog();

                View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.fingerprintimage, null);
                ImageView fingerImageView = (ImageView) view.findViewById(R.id.fingerImageView);
                fingerImageView.setImageBitmap(bitmap);
                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title("指纹图片")
                        .positiveText("指纹图片")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                pDialog.dismiss();
                            }
                        })
                        .build();
                pDialog.show();

            }
        }, new IErrorCallback() {
            @Override
            public void onError(Bundle bundle) {

            }
        }));
//        SiecomDevice.readFingerPic(new DeviceCallback() {
//            @Override
//            public void onStart() {
//
//                if (pDialog != null && pDialog.isShowing()) {
//                    pDialog.dismiss();
//
//                }
//                pDialog = null;
//                View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.layout_finger_scan, null);
//                scan_line = (ImageView) view.findViewById(R.id.lockscreen_scan_line);
//                upAnimation = AnimationUtils.loadAnimation(ChangAnActivity.this, R.anim.push_up_in);
//                upAnimation.setFillAfter(true);
//                upAnimation.setAnimationListener(new UpAnimationOnListener());
//
//                downAnimation = AnimationUtils.loadAnimation(ChangAnActivity.this, R.anim.push_up_out);
//                downAnimation.setFillAfter(true);
//                downAnimation.setAnimationListener(new DownAnimationOnListener());
//                scan_line.startAnimation(downAnimation);
//
//                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
//                        .theme(Theme.DARK)
//                        .customView(view, true)
//                        .title(R.string.read_fingerimg)
//                        .positiveText(R.string.no)
//                        .cancelable(false)
//                        .dismissListener(new DialogInterface.OnDismissListener() {
//                            @Override
//                            public void onDismiss(DialogInterface dialog) {
//                                /**
//                                 * 取消任务；
//                                 */
//                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
//                                    @Override
//                                    public void onStart() {
//
//                                    }
//
//                                    @Override
//                                    public void onError(Bundle bundle) {
//
//                                    }
//
//                                    @Override
//                                    public void onSuccess(Bundle bundle) {
//
//                                        Toast.makeText(ChangAnActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();
//
//                                    }
//
//                                    @Override
//                                    public void onCompleted(Bundle bundle) {
//
//                                    }
//                                }, 2000, true);
//
//
//                            }
//                        })
//                        .onPositive(new MaterialDialog.SingleButtonCallback() {
//                            @Override
//                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
//                                dismissDialog();
//                                Snackbar.make(mLinearLayout, "取消指纹后再启动最长可能需要5~7秒", Snackbar.LENGTH_LONG).setAction("Action", null).show();
//
//                            }
//                        })
//                        .build();
//
//                pDialog.show();
//
//                Snackbar.make(mLinearLayout, "您可以放开手指了,开始传输图像", Snackbar.LENGTH_LONG).setAction("Action", null).show();
//            }
//
//            @Override
//            public void onError(Bundle bundle) {
//                mFailCount++;
//                dismissDialog();
//                Snackbar.make(mLinearLayout, "指纹图片错误", Snackbar.LENGTH_LONG).setAction("Action", null).show();
//            }
//
//            @Override
//            public void onSuccess(Bundle bundle) {
//                mSuccessCount++;
//                dismissDialog();
//                /**
//                 * 获取到指纹特征码，默认使用Base64转一下
//                 */
//                dismissDialog();
//                Bitmap bm = bundle.getParcelable("Img");
//                View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.fingerprintimage, null);
//                ImageView fingerImageView = (ImageView) view.findViewById(R.id.fingerImageView);
//                fingerImageView.setImageBitmap(bm);
//                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
//                        .theme(Theme.DARK)
//                        .customView(view, true)
//                        .title("指纹图片")
//                        .positiveText("指纹图片")
//                        .onPositive(new MaterialDialog.SingleButtonCallback() {
//                            @Override
//                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
//                                pDialog.dismiss();
//                            }
//                        })
//                        .build();
//                pDialog.show();
//
//                Snackbar.make(mLinearLayout, "总耗时：" + (System.currentTimeMillis() - now) + "ms", Snackbar.LENGTH_LONG).setAction("Action", null).show();
//
//
//            }
//
//            @Override
//            public void onCompleted(Bundle bundle) {
////                now = System.currentTimeMillis();
////                pDialog.setTitle("成功"+ mSuccessCount+"次，"+ "失败" + mFailCount + "次");
//            }
//        }, 30000, true);


    }

    TextView mTrackTV;
    private void getSingature() {
        Log.e("read", "getSingature");
        now = System.currentTimeMillis();
//
        final Task task = new Task(Task.Operate.SIGNATURE, new ISucceedCallback() {
            @Override
            public void onSucceed(Bundle bundle) {
                Bitmap bitmap = bundle.getParcelable("bitmap");
                String track = bundle.getString("spotStr");
                LogUtil.e(TAG,"size == " + bitmap.getByteCount() + "---- track == " + track);
                dismissDialog();
                View view = LayoutInflater.from(ChangAnActivity.this).inflate(R.layout.signature_dialog, null);
                Bitmap signature = bundle.getParcelable("data");
                ImageView imageView = (ImageView) view.findViewById(R.id.signatureImageView);
                mTrackTV = (TextView) view.findViewById(R.id.tv_track_data);
                imageView.setImageBitmap(signature);
//                saveBitmapTofile(signature,path + "phonessssssssssss.png");
                pDialog = new MaterialDialog.Builder(ChangAnActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title(R.string.read_signature)
                        .positiveText(R.string.no)
                        .cancelable(true)
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {

                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();

                            }
                        })
                        .build();
                pDialog.show();

            }
        }, new IErrorCallback() {
            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = peripheral.getErrorMessage(code);
                LogUtil.e(TAG,"msg == " + msg + " ============ " + bundle.getString("MSG"));
            }
        });
//        task.setSignatureWidthAndHeight(1080,960);
        peripheral.addTask(task);


    }


    /**
     * 监听蓝牙状态
     */
    private void connectStatusListen() {

        SiecomDevice.connectStatusChange(new ConnectStatusCallback() {
            @Override
            public void onConnectStart() {
                Log.e("connectStatusChange", "onConnectStart");
            }

            @Override
            public void onConnected() {
                Log.e("connectStatusChange", "onConnected");
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ChangAnActivity.this, "已连接", Toast.LENGTH_SHORT).show();
                        dismissDialog();
                    }
                });
            }

            @Override
            public void onDisConnect(Throwable e) {
                Log.e("connectStatusChange", e.getMessage());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ChangAnActivity.this, "连接已经断开", Toast.LENGTH_SHORT).show();
                        dismissDialog();
                    }
                });


            }
        });
    }

    /**
     * 连接设备
     */
    private void initLink() {
        connectStatusListen();



        String strMac = "";
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : devices){
            if (device.getName().startsWith("A108P")){
                strMac = device.getAddress();
                break;
            }
        }
        if (!TextUtils.isEmpty(strMac)){
            Task task = new Task(Task.Operate.CONNECT_DEVICE, new ISucceedCallback() {
                @Override
                public void onSucceed(Bundle bundle) {

                    LogUtil.e(TAG," CONNECT_DEVICE onSucceed " +  "  -- isConnected == " + peripheral.isConnected());

                    afterLink();
                }
            }, new IErrorCallback() {
                @Override
                public void onError(Bundle bundle) {
                    LogUtil.e(TAG,"没有要连接的设备");
                }
            });
            if (!peripheral.isConnected()){
                peripheral.addTask(task);
            }

        }

    }


    /**
     * 连接设备成功后改变UI
     */
    public void afterLink() {
        spb.progressiveStop();
        deviceName.setTextColor(ContextCompat.getColor(ChangAnActivity.this, R.color.forest_green));
        TransitionDrawable mTransitionDrawable = new TransitionDrawable(new Drawable[]{
                deviceIcon.getDrawable(),
                ContextCompat.getDrawable(ChangAnActivity.this, R.mipmap.connected_black)
        });
        mTransitionDrawable.setCrossFadeEnabled(true);
        mTransitionDrawable.startTransition(1000);
        deviceIcon.setImageDrawable(mTransitionDrawable);
        addUI();

        peripheral.addTask(new Task(Task.Operate.DEVICE_SERIALNUMBER, new ISucceedCallback() {
            @Override
            public void onSucceed(Bundle bundle) {
                LogUtil.e(TAG,"获取序列号 == " + bundle.getString(ConstCA.deviceSerialNumber));
            }
        }, new IErrorCallback() {
            @Override
            public void onError(Bundle bundle) {

            }
        }));

    }


    public void disConnectBlueDevice(){
        SiecomDevice.disConnect(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

            }

            @Override
            public void onSuccess(Bundle bundle) {

            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, true);
    }

    public void disConnectBTP350(){

    }
    /**
     * UI界面
     */
    private void addUI() {
        /*  身份证 */
        LinearLayout rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /**
                 * 读取身份证需要在sd卡上写入授权文件，6.0以上需要检查权限
                 */
                checkPermission(1);


            }
        });
        mLinearLayout.addView(rl);

        /*  指纹 */
        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        TextView tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.read_finger));
        ImageView iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.fingerprint);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                readFingerPrint();
            }

        });


        mLinearLayout.addView(rl);


        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        TextView finger1 = (TextView) rl.findViewById(R.id.read_id);
        finger1.setText(getResources().getString(R.string.read_fingerimg));
        ImageView fingers1 = (ImageView) rl.findViewById(R.id.id_icon);
        fingers1.setImageResource(R.mipmap.fingerprint);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getFingerImageViewPrint();
            }
        });
        mLinearLayout.addView(rl);

        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        TextView finger = (TextView) rl.findViewById(R.id.read_id);
        finger.setText(getResources().getString(R.string.read_signature));
        ImageView fingers = (ImageView) rl.findViewById(R.id.id_icon);
        fingers.setImageResource(R.mipmap.brush);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getSingature();

            }
        });
        mLinearLayout.addView(rl);

        /*密码键盘*/
        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.keyPin));
        iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.keyboard);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showKeyDialog();

            }
        });
        mLinearLayout.addView(rl);


          /*银行卡*/
        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.bankCard));
        iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.ic_credit_card);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showCardDialog();

            }
        });
        mLinearLayout.addView(rl);

        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.other));
        iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.settings_black);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消操作

                showOtherDialog();
            }
        });
        mLinearLayout.addView(rl);

        //测试其他功能
//        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
//        tv = (TextView) rl.findViewById(R.id.read_id);
//        tv.setText(getResources().getString(R.string.other));
//        iv = (ImageView) rl.findViewById(R.id.id_icon);
//        iv.setImageResource(R.mipmap.settings_black);

//        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //取消操作
//                if(packType == 3){
//                    int ret = mUPDDevice.openDevice(ChangAnActivity.this,1);
//                    LogUtil.e(TAG,"openDevice == " + ret);
//
//                }
//            }
//        });
//        mLinearLayout.addView(rl);

        //------------------------
        //initKeySignPad();
        //-------------------------
    }




    /**
     * 取消对话框
     */
    public void dismissDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    /**
     * android API23以上需要检查权限
     */
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;


    public void checkPermission(int code) {
        Log.e("click", "checkPermission");
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    code);
        } else {
            if (code == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
                readIDcard();
            } else {
//                updateBin();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission ok", Toast.LENGTH_SHORT).show();

                readIDcard();

            } else {

                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        } else {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission ok", Toast.LENGTH_SHORT).show();

//                updateBin();

            } else {

                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        if (packType == 0)
            disConnectBlueDevice();

        if (packType == 1)
            disConnectBTP350();


    }

    /**
     * 指纹动画效果
     * 上下扫描
     */
    private class DownAnimationOnListener implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {

            scan_line.startAnimation(upAnimation);

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

    }

    private class UpAnimationOnListener implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {

            scan_line.startAnimation(downAnimation);

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

    }


}




